﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using Kugar.Core.BaseStruct;
using Kugar.Core.ExtMethod;
using Kugar.UI.Web.AdminLTE.Enums;
using Kugar.UI.Web.AdminLTE.Helpers;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc.Rendering;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Kugar.UI.Web.AdminLTE.PageControls.PageCommon
{
    public class PageCommon_DataPicker<TData>:ContainerBase
    {
        private bool _isMultiSelectd = false;
        private string _title = "";
        private List<Action<ButtonConfigBase>> _leftBtnLst=new List<Action<ButtonConfigBase>>();
        private List<Action<ButtonConfigBase>> _rightBtnLst=new List<Action<ButtonConfigBase>>();
        private PageCommon_QueryBox _queryBox = null;
        private string _iconCss = "fa-windows";
        private Lazy<PageCommon_Table2<TData>> _tableValue = null;
        private Func<TData, JObject> _rowJsonDataFunc = null;
        private Func<TData, object> _rowDataFunc = null;
        private string _url = "";
        private string _height = "600px";
        private string _width = "800px";
        private string _selectedAreaTableOrderbyKey = "";
        private int _selectedAreaTableOrderbyType = 0;
        private string _selectedAreaTitle = "已选择:{0}个";

        public PageCommon_DataPicker(ViewContext viewContext) : base(viewContext)
        {
            this.Css("box modalwindow datapicker box-info box-solid");

            _queryBox=new DataPickerQueryBox(this.ViewContext);

            _tableValue=new Lazy<PageCommon_Table2<TData>>(createTable);

            _url = viewContext.HttpContext.Request.GetDisplayUrl();

            _queryBox.Url(_url).Method(viewContext.HttpContext.Request.Method);
        }

        /// <summary>
        /// 是否多选
        /// </summary>
        /// <param name="isMulti"></param>
        /// <returns></returns>
        public PageCommon_DataPicker<TData> MultiSelect(bool isMulti = true)
        {
            _isMultiSelectd = isMulti;

            return this;
        }

        /// <summary>
        /// 取数图标
        /// </summary>
        /// <param name="iconClass"></param>
        /// <returns></returns>
        public PageCommon_DataPicker<TData> IconCss(string iconClass)
        {
            _iconCss = iconClass;
            return this;
        }

        /// <summary>
        /// 选择器标题
        /// </summary>
        /// <param name="title"></param>
        /// <returns></returns>
        public PageCommon_DataPicker<TData> Title(string title)
        {
            _title = title;

            return this;
        }

        /// <summary>
        /// 添加一个底部右侧按钮
        /// </summary>
        /// <param name="btnConfig"></param>
        /// <returns></returns>
        public PageCommon_DataPicker<TData> AddRightButton(Action<ButtonConfigBase> btnConfig)
        {
            _rightBtnLst.Add(btnConfig);

            return this;
        }

        /// <summary>
        /// 添加一个底部左侧按钮
        /// </summary>
        /// <param name="btnConfig"></param>
        /// <returns></returns>
        public PageCommon_DataPicker<TData> AddLeftButton(Action<ButtonConfigBase> btnConfig)
        {
            _leftBtnLst.Add(btnConfig);
            return this;
        }

        /// <summary>
        /// 排序字段
        /// </summary>
        /// <param name="thCssName"></param>
        /// <param name="isAsc">是否为正序</param>
        /// <returns></returns>
        public PageCommon_DataPicker<TData> SelectedAreaTableOrderbyKey(string thCssName,bool isAsc=true)
        {
            _selectedAreaTableOrderbyKey = thCssName;
            _selectedAreaTableOrderbyType = isAsc ? 0 : -1;

            return this;
        }

        /// <summary>
        /// 多选状态下,已选框区域的标题
        /// </summary>
        /// <param name="title">已选区域的标题,如 已选择{0}:  运行时会自动将{0} 替换为已选择的数量</param>
        /// <returns></returns>
        public PageCommon_DataPicker<TData> SelectedAreaTitle(string title)
        {
            _selectedAreaTitle = title;

            return this;
        }

        public PageCommon_DataPicker<TData> ContentHeight(string height)
        {
            _height = height;

            return this;
        }

        public PageCommon_DataPicker<TData> ContentHeight(int height)
        {
            _height = $"{height}px";

            return this;
        }

        public PageCommon_DataPicker<TData> ContentWidth(string width)
        {
            _width = width;

            return this;
        }

        public PageCommon_DataPicker<TData> ContentWidth(int width)
        {
            _width = $"{width}px";

            return this;
        }

        public PageCommon_QueryBox FilterBlock => _queryBox;

        public PageCommon_Table2<TData> Table(IEnumerable<TData> data,Func<TData,JObject> rowDataFunc)
        {
            _rowJsonDataFunc = rowDataFunc;
            _rowDataFunc = null;
            return _tableValue.Value.Data(data);
        }

        public PageCommon_Table2<TData> Table(VM_PagedList<TData> data, Func<TData, JObject> rowDataFunc)
        {
            _rowDataFunc = null;
            _rowJsonDataFunc = rowDataFunc;

            return _tableValue.Value.Data(data);
        }

        public PageCommon_Table2<TData> Table(IEnumerable<TData> data, Func<TData, object> rowDataFunc)
        {
            _rowDataFunc = rowDataFunc;
            _rowJsonDataFunc = null;
            return _tableValue.Value.Data(data);
        }

        public PageCommon_Table2<TData> Table(VM_PagedList<TData> data, Func<TData, object> rowDataFunc)
        {
            _rowDataFunc = rowDataFunc;
            _rowJsonDataFunc = null;
            return _tableValue.Value.Data(data);
        }

        public override void Dispose()
        {
            WriteClearfix();
            
            var writer = ViewContext.Writer;

            if (_isMultiSelectd)
            {
                ViewContext.Writer.WriteLine("<div class=\"box collapsed-box box-warning box-solid no-margin dataPickerSelectedArea\">");

                ViewContext.Writer.WriteLine("<div class=\"box-header with-border\">");
                ViewContext.Writer.WriteLine($"<h5 class=\"box-title selectedAreaTitle\" data-selectedareatitle=\"{_selectedAreaTitle}\">{_selectedAreaTitle}</h5><div class=\"box-tools \"><button type=\"button\" class=\"btn btn-box-tool \" data-widget=\"collapse\"><i class=\"fa fa-plus\"></i></button></div>");
                ViewContext.Writer.WriteLine("<div class=\"box-tools pull-right\"><button type=\"button\" class=\"btn btn-box-tool \"><span class=\"badge bg-red clearselected\">清空所选</span></button></div>");
                ViewContext.Writer.WriteLine("</div> <!-- .box-header -->");


                ViewContext.Writer.WriteLine("<div class=\"box-body\">");
                ViewContext.Writer.WriteLine("<table webui-ignore class=\"table table-condensed dataPickerSelectedItems\">");
                ViewContext.Writer.WriteLine("<thead><tr>");

                ViewContext.Writer.WriteLine("<th style=\"width: 20px\"><i class=\"fa fa-arrows-alt\"></i></th>");

                for (int i = 1; i < _tableValue.Value.Columns._columns.Count; i++)
                {
                    var column = _tableValue.Value.Columns._columns[i];

                    ViewContext.Writer.WriteLine(column.RenderHeader());
                }

                ViewContext.Writer.WriteLine("</tr></thead>");

                ViewContext.Writer.WriteLine("<tbody></tbody>");

                ViewContext.Writer.WriteLine("</table>");
                ViewContext.Writer.WriteLine("</div>");

                ViewContext.Writer.WriteLine("</div> <!-- .dataPickerSelectedArea -->");

            }
            
            writer.WriteLine("</div> <!-- .datapickercontent_inner-->");

            writer.WriteLine("</div> <!-- .box-body .datapickercontent-->");
            
            if (_isMultiSelectd || _leftBtnLst.HasData() || _rightBtnLst.HasData())
            {
                writer.WriteLine("<div class=\"box-footer modalfooter datapickerfooter\">");
                
                //多选时,输出两个固定按钮
                writer.WriteLine("<div class=\"buttonarea\">");

               
                if (_leftBtnLst.HasData())
                {
                    ViewContext.Writer.WriteLine("<div class=\"leftbuttonarea\">");

                    foreach (var btn in _rightBtnLst)
                    {
                        var config = new ButtonConfigBase(ViewContext);
                        config.Css("btn");

                        btn(config);

                        if (config._hide)
                        {
                            continue;
                        }


                        config.Css("btn-" + config._color);

                        writer.WriteLine($"<button {config.Attributes}>{config._iconHtml}{config._title}</button>");
                    }

                    ViewContext.Writer.WriteLine("</div>");
                }

                if (_rightBtnLst.HasData() || _isMultiSelectd)
                {
                    ViewContext.Writer.WriteLine("<div class=\"rightbuttonarea\">");

                    foreach (var btn in _rightBtnLst)
                    {
                        var config = new ButtonConfigBase(ViewContext);
                        config.Css("btn");

                        btn(config);

                        if (config._hide)
                        {
                            continue;
                        }

                        config.Css("btn-" + config._color);

                        writer.WriteLine($"<button {config.Attributes}>{config._iconHtml}{config._title}</button>");
                    }

                    if (_isMultiSelectd)
                    {
                        writer.WriteLine("<button type=\"button\" webui-ignore class=\"btn btn-success okbutton\" >选择</button>");

                        writer.WriteLine("<button type=\"button\" webui-ignore class=\"btn btn-default cancelbutton\">取消</button>");
                    }
                    
                    ViewContext.Writer.WriteLine("</div>");
                }

                WriteClearfix();

                writer.WriteLine("</div> <!-- .buttonarea -->");

                writer.WriteLine("</div> <!-- .box-footer .datapickerfooter -->");
            }


            writer.WriteLine("</div> <!-- .box -->");
        }

        internal override ContainerBase RenderInternal()
        {
            if (_isMultiSelectd)
            {
                
            }

            var writer = ViewContext.Writer;

            writer.WriteLine($"<div {Attributes} data-orderby=\"{_selectedAreaTableOrderbyKey}\" data-orderbytype=\"{_selectedAreaTableOrderbyType}\" data-selectedareatitle=\"{_selectedAreaTitle}\" >");
            writer.WriteLine($"<div class=\"box-header with-border modaltitle\"><h4 class=\"box-title\"><i class=\"fa {_iconCss}\" style=\"margin-right: 10px\"></i>{_title}</h4></div>");
            
            writer.WriteLine($"<div class=\"box-body modalcontent no-padding datapickercontent\" style=\"height:{_height};width:{_width};max-width:100%;\">");

            ViewContext.Writer.WriteLine($"<div class=\"datapickercontent_inner\" style=\"width:{_width};max-width:100%;\">");

            return this;
        }

        private PageCommon_Table2<TData> createTable()
        {
            var tableValue = new DataPickerTable<TData>(this.ViewContext).Type(DataTableTypeEnum.WebUITable).ScrollY(440);

            if (_rowDataFunc != null)
            {
                _rowJsonDataFunc = (x) => JObject.FromObject(_rowDataFunc(x));
                tableValue.RowData(_rowJsonDataFunc);
            }
            


            if (_isMultiSelectd)
            {
                tableValue.Columns.AddCheckbox().Value(x => HttpUtility.HtmlEncode(_rowJsonDataFunc(x).ToStringEx(Formatting.None)));
            }
            else
            {
                tableValue.AddRowHiddenValue(x=>("rowdata", HttpUtility.HtmlEncode(_rowJsonDataFunc(x).ToStringEx(Formatting.None))));
            }

            return tableValue;
        }

        public class DataPickerTable<Data> : PageCommon_Table2<Data>
        {
            public DataPickerTable(ViewContext viewContext) : base(viewContext)
            {
                this.Attr("webui-ignore","");
                //this.DisabledLoading();
            }

            internal override ContainerBase RenderInternal()
            {
                ViewContext.Writer.WriteLine("<div class=\"dataPickerDataList\">");
                return base.RenderInternal();
            }

            public override void Dispose()
            {
                base.Dispose();
                WriteClearfix();
                ViewContext.Writer.WriteLine("</div> <!-- .dataPickerDataList -->");

                
            }
        }

        public class DataPickerQueryBox : PageCommon_QueryBox
        {
            public DataPickerQueryBox(ViewContext viewContext) : base(viewContext)
            {
                this.Attr("webui-ignore", "");
            }
        }
    }
}
